package com.qigao.erp.commons.utils;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author luiz
 * @Title: com.qigao.erp.commons.utils
 * @ProjectName three-mall
 * @date 2019-11-2019/11/21 16:18
 * @Description:
 */
public class AESUtil {
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";
    /**
     * 生成key
     */


    /**
     * AES加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String md5Key, String data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(MD5Util.getMD5(md5Key).toLowerCase().getBytes(), ALGORITHM);
        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return Base64Utils.encode(cipher.doFinal(data.getBytes()));
    }

    /**
     * AES解密
     *
     *
     * @param md5Key
     * @param base64Data
     * @return
     * @throws Exception
     */
    public static String decryptData(String md5Key, String base64Data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(MD5Util.getMD5(md5Key).toLowerCase().getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return new String(cipher.doFinal(Base64Utils.decode(base64Data)));
    }
}
